/// <reference path="../base.js" />
/// <reference path="../3rdParty/Mootools-Core.js" />

Global.Pricelists[Global.CurrentPricelist] = Utility.Pricelist.GetBlank();

Panels.Pricelist.Init = function()
{
  var table = $("PricelistTableArea");
  var html = "<table>"
           + "<tr>"
           + "<th align='center'>Commodity</th>"
           + "<th align='center'>Buy Price</th>"
           + "<th align='center'>Sell Price</th>"
           + "</tr>";

  for (var commodity in Global.Commodities)
  {
    if (!Global.Commodities.hasOwnProperty(commodity))
      continue;

    html += "<tr>"
          + "<td>" + commodity + "</td>"
          + "<td><input type='text' size='4' id='" + commodity + "BuyPrice' value='0' onBlur='Panels.Pricelist.Set(this);' /></td>"
          + "<td><input type='text' size='4' id='" + commodity + "SellPrice' value='0' onBlur='Panels.Pricelist.Set(this);' /></td>"
          + "</tr>";
  }

  html += "</table>";
  table.set("html", html);
}

window.addEvent("domready", Panels.Pricelist.Init);

Panels.Pricelist.Set = function(element)
{
  var commodity = element.get("id").replace("BuyPrice", "").replace("SellPrice", "");
  var value = element.get("value").toInt();

  if (value == NaN || value == "NaN")
    value = 0;

  element.set("value", value);

  if (element.get("id").search("BuyPrice") != -1) // Buy Price
  {
    Utility.Pricelist.SetBuy(commodity, value);
  }
  else
  {
    Utility.Pricelist.SetSell(commodity, value);
  }
}

Panels.Pricelist.Render = function(pricelist)
{
  if (pricelist == undefined)
    pricelist = Global.Pricelists[Global.CurrentPricelist];

  $("PricelistName").set("value", pricelist.name);

  for (var commodity in pricelist.buy)
  {
    if (!pricelist.buy.hasOwnProperty(commodity))
      continue;

    $(commodity + "BuyPrice").set("value", pricelist.buy[commodity]);
    $(commodity + "SellPrice").set("value", pricelist.sell[commodity]);
  }
}